﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using WarehouseManagement.Shared.Settings;
using System.Linq;
using WarehouseManagement.Shared;
using System.IO;

namespace WarehouseManagement.Views.Login
{
    public partial class ServerConfig : DevExpress.XtraEditors.XtraForm
    {
        private DatabaseSettings _settings;
        private string filePath;

        public ServerConfig()
        {
            InitializeComponent();
            _settings = new DatabaseSettings();
            filePath = GlobalMemory.DatabaseSettingFilePath;
        }

        private void ServerConfig_Load(object sender, EventArgs e)
        {
            radAuth.SelectedIndex = 0;
            try
            {
                LoadSettings();
            }
            catch (FileNotFoundException)
            {
                btnCreateDB.Visible = true;
            }
        }
        private void LoadSettings()
        {
            _settings = SettingsManager.ReadSettings(filePath);
            txtDatabaseName.Text = _settings.DatabaseName;
            txtServerName.Text = _settings.ServerName;
            txtUsername.Text = _settings.Username;
            txtPassword.Text = _settings.Password;
            radAuth.SelectedIndex = _settings.WindowsAuthentication ? 0 : 1;
        }
        private void radAuth_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtUsername.Properties.ReadOnly = txtPassword.Properties.ReadOnly = radAuth.SelectedIndex == 0;
        }

        private void UpdateSettings()
        {
            _settings.DatabaseName = txtDatabaseName.Text;
            _settings.ServerName = txtServerName.Text;
            _settings.Username = txtUsername.Text;
            _settings.Password = txtPassword.Text;
            _settings.WindowsAuthentication = radAuth.SelectedIndex == 0;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {

            if (!TestConnection())
            {
                XtraMessageBox.Show("Không thể kết nối tới máy chủ", "Lỗi kết nối", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                SettingsManager.SaveSettings(_settings, filePath);
                XtraMessageBox.Show("Thiết lập máy chủ thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Restart();
            }
            catch
            {
                XtraMessageBox.Show("Không thể thiết lập máy chủ. Xin hãy thử lại sau", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private bool TestConnection()
        {
            UpdateSettings();
            var conStr = _settings.ConnectionString;
            try
            {
                var sqlConn = new SqlConnection(conStr);
                var sqlServer = new Server(new ServerConnection(sqlConn));
                var a = sqlServer.Databases.Count;
                return true;
            }
            catch { return false; }
        }

        private void ExecuteCreateDBSqlScript()
        {
            DatabaseSettings st2 = new DatabaseSettings(_settings);
            st2.DatabaseName = "master";


            string sqlConnectionString = st2.ConnectionString;
            FileInfo file = new FileInfo(string.Format("{0}\\database_gen.sql", Application.StartupPath));
            string script = file.OpenText().ReadToEnd();
            SqlConnection conn = new SqlConnection(sqlConnectionString);
            Server server = new Server(new ServerConnection(conn));

            var script1 = string.Format("Create database {0}", txtDatabaseName.Text);
            server.ConnectionContext.ExecuteNonQuery(script1);
            script1 = string.Format("Use {0}", txtDatabaseName.Text);
            server.ConnectionContext.ExecuteNonQuery(script1);

            server.ConnectionContext.ExecuteNonQuery(script);
        }

        private void LoadDatabaseNameFromServer()
        {
            UpdateSettings();
            //var conStr = _settings.ConnectionString;
            var setting2 = _settings;
            setting2.DatabaseName = "master";
            //var conStr =  "Data Source=(local);Initial Catalog=master;User ID=sa;Password=sa; Integrated Security=true;";
            var conStr = setting2.ConnectionString;

            var sqlConn = new SqlConnection(conStr);
            var sqlServer = new Server(new ServerConnection(sqlConn));


            txtDatabaseName.Properties.Items.Clear();
            foreach (Database db in sqlServer.Databases)
            {
                txtDatabaseName.Properties.Items.Add(db.Name);
            }


        }


        private void txtDatabaseName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)
            {
                if (txtDatabaseName.Properties.Items.Count > 0)
                {
                    return;
                }
            };


            try
            {
                txtDatabaseName.Enabled = false;
                LoadDatabaseNameFromServer();

            }
            catch
            {
                XtraMessageBox.Show("Không thể kết nối tới máy chủ", "Lỗi kết nối", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                txtDatabaseName.Enabled = true;
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCreateDB_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtDatabaseName.Text))
            {
                XtraMessageBox.Show("Bạn hãy nhập tên CSDL", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                LoadDatabaseNameFromServer();
            }
            catch
            {
                XtraMessageBox.Show("Không thể kết nối tới máy chủ", "Lỗi kết nối", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ContainDb(txtDatabaseName.Text))
            {
                XtraMessageBox.Show(string.Format("Đã tồn tại CSDL có tên {0}", txtDatabaseName.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                ExecuteCreateDBSqlScript();
                XtraMessageBox.Show(string.Format("Đã tạo CSDL '{0}'", txtDatabaseName.Text), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnSave_Click(this, e);
            }
            catch (Exception)
            {
                XtraMessageBox.Show(string.Format("Không thể tạo CSDL"), "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool ContainDb(string dbName)
        {
            foreach (var item in txtDatabaseName.Properties.Items)
            {
                if (item.Equals(dbName)) return true;
            }
            return false;
        }

        private string GetCreateDBSqlScript()
        {
            return "";
        }
    }
}